package com.itheima.service.impl;

import com.itheima.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.vo.MenuVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;

import java.util.*;

/**
 * @author admin
 */
@DubboService
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public List<MenuVO> findMenuByUserName(String userName) {
        return doQuery(baseMapper.findMenuByUserName(userName));
    }

    @Override
    public List<MenuVO> findAllMenu() {
        return doQuery(baseMapper.findAllMenu());
    }

    public List<MenuVO> doQuery(List<MenuVO> menuVoList) {
        if (menuVoList != null) {
            Map<Long, MenuVO> menuVoMap = new HashMap<>();
            menuVoList.forEach(menuVo ->
                    menuVoMap.put(menuVo.getId(), menuVo)
            );
            menuVoList.clear();
            for (MenuVO menuVo : menuVoMap.values()) {
                Long pid = menuVo.getPid();
                MenuVO parent = menuVoMap.get(pid);
                if (parent == null) {
                    menuVoList.add(menuVo);
                } else {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(menuVo);
                }
            }
            return menuVoList;
        }
        return null;
    }


}